package com.example.securitydemo.utils;

import com.example.core.utils.JwtUtils;
import com.example.securitydemo.authentication.MyUserDetailsService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

/**
 * @author Cary
 * @date 2022/3/25
 */
@Component
public class TokenUtils extends JwtUtils {
    @Autowired
    private MyUserDetailsService myUserDetailsService;

    public String generateToken(Authentication authentication) {
        return generateToken(authentication.getName());
    }

    public boolean validateToken(String token) {
        try {
            getClaimByToken(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public Authentication getAuthentication(String token) {
        Claims claims = getClaimByToken(token);
        String userName = String.valueOf(claims.getSubject());
        UserDetails userDetails = myUserDetailsService.loadUserByUsername(userName);
        return new UsernamePasswordAuthenticationToken(userDetails, token, userDetails.getAuthorities());
    }
}
